import { Message, MessageBox } from 'element-ui'
import { emptyCellText } from '@/env'

// 工具函数
const toType = (obj) => {
  return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase()
}

const OnceMsg = function (fn) {
  let called = false
  return function (message) {
    if (called) {
      return
    }
    called = true
    Message[fn]({
      message,
      onClose: () => {
        called = false
      }
    })
  }
}

const Once = (type) => {
  let called = false
  return function (options) {
    if (called) return
    called = true
    if (options.callback) {
      let cb = options.callback
      options.callback = function (...args) {
        // eslint-disable-next-line standard/no-callback-literal
        cb(...args)
        called = false
      }
    }
    const { message = '', title = '提示', ...rest } = options
    MessageBox[type](message, title, rest)
  }
}

const onceAlert = Once('alert')
const onceError = OnceMsg('error')

const actionIconMap = {
  view: 'fa fa-eye',
  update: 'fa fa-edit',
  delete: 'el-icon-delete'
}

const noop = () => {
}

const isObject = (obj) => obj !== null && typeof obj === 'object'

const isFunction = (obj) => typeof obj === 'function'

const isPromise = (value) => isObject(value) && isFunction(value.then)

const formatTime = date => {
  if (!date) return emptyCellText

  try {
    if (!(date instanceof Date)) {
      date = new Date(date)
    }
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  } catch (e) {
    return date
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export {
  actionIconMap,
  onceAlert,
  onceError,
  toType,
  noop,
  isFunction,
  isPromise,
  formatTime,
  formatNumber
}
